﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using Aesha.WoW.Broker.Data;
using Aesha.WoW.Broker.Model;

namespace Aesha.WoW.Broker.Infrastructure
{
    internal class BrokerRepository
    {
        private readonly BrokerContext _db = new BrokerContext();

        public bool ItemExists(int itemId)
        {
            var item = (from i in _db.Items
                        where i.ItemId == itemId
                        select i).SingleOrDefault();

            return item != null;
        }

        public Item GetItem(int itemId)
        {
            var item = (from i in _db.Items
                        where i.ItemId == itemId
                        select i).SingleOrDefault();

            return item;
        }

        public List<int> GetCachItemIds()
        {
            var itemIds = from i in _db.Items
                          select i.ItemId;

            return itemIds.ToList();
        }

        public void RefreshItemClasses(List<ItemClass> itemClasses )
        {
            _db.Database.ExecuteSqlCommand("DELETE FROM [ItemSubClass]");
            _db.Database.ExecuteSqlCommand("DELETE FROM [ItemClass]");

            foreach (var ic in itemClasses)
            {
                _db.ItemClasses.Add(ic);
            }

            _db.SaveChanges();
        }

        public void CacheItem(Item item)
        {
            try
            {
                _db.Items.Add(item);
                _db.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                var validationError = ex.EntityValidationErrors.FirstOrDefault();
            }
        }
    }
}
